<script setup lang="ts">
import { roleApi } from "@/api/admin/role";
import {
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElTree,
  ElButton,
  ElMessage,
} from "element-plus";
import { nextTick, ref } from "vue";
const isEditor = ref(false);
const visible = ref(false);
const treeRef = ref<any>(null);
class RoleForm {
  name = "";
  remark = "";
  menus = [];
}

const roleForm = ref(new RoleForm());

const roleFormRef = ref<any>(null);

const roleMenuKeys = ref<any>([]);

const emit = defineEmits(["update"]);

const props = defineProps({
  menuTree: {
    type: Array,
    default: () => [],
  },
});

// 打开弹窗
const open = (data: any = null) => {
  visible.value = true;
  if (data) {
    isEditor.value = true;
    nextTick(() => {
      roleForm.value = data;
      const ids = data.menus.map((item: any) => item.id);
      roleMenuKeys.value = ids;
      treeRef.value.setCheckedKeys(ids);
    });
  } else {
    roleForm.value = new RoleForm();
    isEditor.value = false;
  }
};

// 清除表单数据
const clearForm = () => {
  roleFormRef.value.resetFields();
  treeRef.value.setCheckedKeys([]);
};

// 关闭弹窗
const handleClose = (deno: () => void) => {
  clearForm();
  deno();
};

// 自定义树节点类名
const customNodeClass = (data: any) => {
  if (data.children && data.children.length > 1) {
    return "is-tow-children";
  }
  return "";
};

// 取消
const handleCancel = () => {
  clearForm();
  visible.value = false;
};

// 确定
const handleOk = async () => {
  await roleFormRef.value.validate();
  const menuList = treeRef.value.getCheckedKeys();
  roleForm.value.menus = menuList;
  // console.log(roleForm.value);
  let ret = null;
  if (!isEditor.value) {
    ret = await roleApi.saveRoleApi(roleForm.value);
  } else {
    ret = await roleApi.updateRoleApi(roleForm.value);
  }
  if (ret.code === 200) {
    // console.log(ret);
    const msgTxt = isEditor ? "修改" : "添加";
    ElMessage.success(`${msgTxt}成功`);
    emit("update");
    handleCancel();
  } else {
    console.error(ret);
    ElMessage.error(ret.data.msg);
  }
};

// 暴露方法
defineExpose({
  open,
});
</script>

<template>
  <el-dialog
    :title="isEditor ? '修改' : '新增'"
    :before-close="handleClose"
    v-model="visible"
  >
    <el-form
      ref="roleFormRef"
      :model="roleForm"
      label-position="right"
      label-width="80px"
    >
      <el-form-item
        prop="name"
        label="角色名称"
        :rules="[{ required: true, message: '请输入角色名称' }]"
      >
        <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item prop="remark" label="角色备注">
        <el-input v-model="roleForm.remark" placeholder="请输入角色备注" />
      </el-form-item>
      <el-form-item prop="menus" label="菜单权限">
        <el-tree
          :default-checked-keys="roleMenuKeys"
          ref="treeRef"
          :highlight-current="true"
          :check-on-click-node="false"
          class="menu-tree"
          default-expand-all
          node-key="id"
          :props="{
            children: 'children',
            label: (node: any) => node.meta.title,
            class: customNodeClass 
          }"
          :data="props.menuTree"
          show-checkbox
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleOk">
          {{ isEditor ? "提交修改" : "添加" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="less" scoped>
:deep(.is-tow-children) {
  .el-tree-node__content {
    color: #626aef;
  }
}

:deep(.menu-tree) {
  .is-tow-children {
    .el-tree-node__children {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
    }
  }
}
</style>
